package com.zhuoyue.biz.core.api.service.impl;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhuoyue.biz.core.api.dao.SysThirdDataMapper;
import com.zhuoyue.biz.core.api.domain.MessageDO;
import com.zhuoyue.biz.core.api.domain.third.JpushDO;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.zhuoyue.biz.core.api.dao.MessageDao;
import com.zhuoyue.biz.core.api.service.JpushService;
import com.zhuoyue.common.constant.MessageCode;
import com.zhuoyue.service.base.ServiceException;
import com.zhuoyue.service.base.ServiceResult;

import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;


/**
 * 极光推送
 *
 * @author Administrator
 */
@Service("jPushService")
public class JpushServiceImpl implements JpushService {

    @Autowired
    private MessageDao messageDao;
    @Value("${spring.profiles.active}")
    private String env;
    @Value("${topic.rabbit.userAddTransferHomeMessage}")
    private String userAddTransferHomeMessage;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private SysThirdDataMapper thirdDataMapper;

    @Override
    public ServiceResult send(String title, String message, String messageType, String registrationId,
                              String extrasType, String extrasContent, String userId, String sourceType, String organization) {

        JpushDO jpush = thirdDataMapper.selectJpushMessage(organization);
        JPushClient jPushClient = new JPushClient(jpush.getSecret(), jpush.getDataKey());

        // 保存消息
        MessageDO build = null;
        try {
            build = MessageDO.builder().sender(registrationId).sendType(MessageCode.JPUSH_TYPE)
                    .messageType(messageType).title(jpush.getTitle()).content(message).type("6")
                    .userId(userId).extras(extrasContent).build();
            Map<String, Object> map = JSONObject.parseObject(JSON.toJSONString(build));
            rabbitTemplate.convertAndSend(userAddTransferHomeMessage, map);
        } catch (Exception e) {
            System.out.println("转移家庭信息保存失败 = " + build);
            System.out.println("异常信息为: = " + e.getMessage());
        }


        //推送
        Map<String, String> extrasMap = new HashMap<>(5);

        PushPayload payload = null;
        String sourceTypeApple = "1";
        try {
            //安卓正常推送，苹果静默推送
            PushResult result = null;
            extrasMap.put("type", extrasType);
            extrasMap.put("content", extrasContent);
            extrasMap.put("ios", message);
            payload = buildPushObjectAllAliasAlert(jpush.getTitle(), message, extrasMap, Audience.registrationId(registrationId), jpush.getUriActivity(), jpush.getUriAction());
            result = jPushClient.sendPush(payload);
            System.out.println(result.isResultOK() + "-" + result.getResponseCode() + "-" + result.getOriginalContent());

            //苹果正常推送
            if (sourceTypeApple.equals(sourceType)) {
                //由于服务器发送速度比较快，极光推送发过去以后苹果会收不到两条消息，所以需要延迟500毫秒
                Thread.sleep(500);
                extrasMap.put("type", extrasType);
                extrasMap.put("content", null);
                payload = buildPushObjectIosTagAndAlertWithExtrasAndMessage(jpush.getTitle(), message, extrasMap, Audience.registrationId(registrationId));
                result = jPushClient.sendPush(payload);
                System.out.println(result.isResultOK() + "-" + result.getResponseCode() + "-" + result.getOriginalContent());
            }

            if (!result.isResultOK()) {
                throw new ServiceException(String.valueOf(result.getResponseCode()), result.getOriginalContent());
            }
        } catch (Exception e) {
            System.out.printf("推送异常" + e.getMessage());
        }


        return new ServiceResult();
    }


    /**
     * 构建推送对象
     * 安卓的正常推送IOS静默推送
     *
     * @param title
     * @param message
     * @param extras
     * @param audience
     * @return
     * @throws Exception
     */
    public PushPayload buildPushObjectAllAliasAlert(String title, String message, Map<String, String> extras, Audience audience, String uriActivity, String uriAction) {
        // 指定要推送的平台，all代表当前应用配置了的所有平台，也可以传android等具体平台
        return PushPayload.newBuilder().setPlatform(Platform.all())
                // 指定推送的接收对象，all代表所有人，也可以指定已经设置成功的tag或alias或应用客户端调用接口获取到的registrationID
                .setAudience(audience)
                // 发送通知
                .setNotification(Notification.newBuilder()
                        // Android
                        .addPlatformNotification(AndroidNotification.newBuilder().setAlert(message).setTitle(title)
                                .addExtras(extras).addExtra("uri_activity", uriActivity).addCustom("uri_activity", uriActivity).addCustom("uri_action", uriAction)
                                .addExtra("uri_action", uriAction).build())

                        // Ios
                        .addPlatformNotification(IosNotification.newBuilder().setAlert("").setBadge(0)
                                .addExtras(extras).setContentAvailable(true).build())
                        .build())
                // 发送消息
                .setMessage(Message.newBuilder().setMsgContent(message).addExtras(extras).build())
                // 设置ios平台Apns环境 True 表示推送生产环境，False 表示要推送开发环境 默认是开发
                .setOptions(Options.newBuilder().setApnsProduction("prod".equals(env)).setTimeToLive(864000).build()).build();
    }


    /**
     * ios第一条的推送
     *
     * @param title
     * @param message
     * @param extras
     * @param audience
     * @return 推送的信息
     */
    public PushPayload buildPushObjectIosTagAndAlertWithExtrasAndMessage(String title, String message, Map<String, String> extras, Audience audience) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(audience)
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(message)
                                .setSound("default")
                                .addExtras(extras).setBadge(0)
//								.setContentAvailable(false)
                                .build())
                        .build())
                .setMessage(Message.newBuilder().setMsgContent(message).addExtras(extras).build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction("prod".equals(env))
                        .build())
                .build();
    }

}
